package com.powerunion.datacollection.workflow.impl;

import java.util.Date;

import net.sf.json.JSONObject;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.powerunion.datacollection.common.BsResponse;
import com.powerunion.datacollection.common.Constants;
import com.powerunion.datacollection.common.Format;
import com.powerunion.datacollection.common.SystemException;
import com.powerunion.datacollection.model.ItemInfo;
import com.powerunion.datacollection.model.jsonObject.CollectionTaskInstanceJO;
import com.powerunion.datacollection.service.CollectionTaskManager;
import com.powerunion.datacollection.service.ItemManager;
import com.powerunion.datacollection.service.ProcessInfoManager;
import com.powerunion.datacollection.service.ProcessInstanceManager;
import com.powerunion.datacollection.workflow.EngineContext;
import com.powerunion.datacollection.workflow.IWorkflowEngine;
import com.powerunion.datacollection.workflow.domain.TaskInstance;
import com.powerunion.util.log.LogHelper;

public class WorkflowEngine implements IWorkflowEngine{
	private static Logger logger = LogHelper.getInstance().getLogger(
			WorkflowEngine.class);
	
	protected EngineContext engineContex = null;
	
	public WorkflowEngine(EngineContext ecx){
		this.engineContex = ecx;
	}
	
	public EngineContext getEngineContext() { 
		return this.engineContex;
	}
	
	public void setEngineContex(EngineContext engineContex) {
		this.engineContex = engineContex;
	}

	
	public BsResponse startupTask(String workflowProcess, String creatorId)
			throws Exception {
		// 参数为空
		if (StringUtils.isEmpty(workflowProcess)) {
			String[] args = { "workflowProcess" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter workflowProcess NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		
		// 参数为空
		if (StringUtils.isEmpty(creatorId)) {
			String[] args = { "creatorId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter creatorId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}

		BsResponse bsResponse = new BsResponse();
		
		JSONObject jsonObject = JSONObject.fromObject(workflowProcess);
		CollectionTaskInstanceJO ctjo = (CollectionTaskInstanceJO) JSONObject
				.toBean(jsonObject, CollectionTaskInstanceJO.class);
		TaskInstance ck = new TaskInstance();

		//复制属性值
		BeanUtils.copyProperties(ck, ctjo);

		ck.setCreateDate(new Date());
		String createDate = Format.getInstance().dateToString(new Date(), "yyyy-MM-dd HH:mm:ss");
		
		ck.setCrtUserCode(creatorId);
		
		ProcessInfoManager pm = new ProcessInfoManager();
		String validateStr = pm.validateActivityInfo(ck.getProcId());
		if(StringUtils.isBlank(validateStr)){
			String itemInfo = ck.getProcItemInfo();
			String proInfo = ck.getProcActInfo();
			String itemId = "";
			ProcessInstanceManager pim = new ProcessInstanceManager();
			ItemManager itm = new ItemManager();
			//查找该任务实例是否已经绑定流程实例信息
			ItemInfo itfo = itm
					.findByKey(ck.getProcId(), Constants.PROINSTANCE);
			if (StringUtils.isEmpty(itemInfo) && StringUtils.isEmpty(proInfo)) {//流程信息为空
				if (StringUtils.isEmpty(itfo.getId())) {//为空则说明还没有绑定流程实例信息，则从流程定义信息拷贝一份数据生成流程实例信息
					itemId = pim.copyProcInfo(ck.getProcId(), creatorId,createDate);
				} else {
					itemId = itfo.getId();
				}
			} else {//非空则说明用户在前台修改了流程信息
				if (StringUtils.isEmpty(itfo.getId())) {//流程实例为空，则说明是第一次创建任务实例修改的是流程定义信息而非是修改任务实例中的流程实例信息
					itemId = pim.save(proInfo, creatorId, itemInfo, ck
							.getProcId(),createDate);
				} else {//流程实例非空，则说明修改的是任务实例中的流程实例
					String proDefineID = pim.getProcDefineId(itfo.getId());
					//得到保存后的流程实例的id
					itemId = pim.save(proInfo, creatorId, itemInfo,
							proDefineID,createDate);
				}
			}

			if (StringUtils.isEmpty(itemId)) {
				bsResponse.setReturnFlag(BsResponse.FATAL_ERR_FLAG);
			} else {
				//设置保存后的流程实例id的值
				ck.setProcId(itemId);
				//保存任务实例
				TaskInstance collectionTaskInstance = this.engineContex.getTaskService().save(ck);
				
				if (collectionTaskInstance != null) {
					boolean flag = pim.initSubmissionWorkItems(
							collectionTaskInstance.getProcId(),
							collectionTaskInstance.getFormId());
					if (flag) {
						//更新任务实例的状态
						this.dao.updateTaskInstanceState(collectionTaskInstance
								.getId(), 1);
						//更新任务信息定义表中的任务实例个数字段
						CollectionTaskManager ctm = new CollectionTaskManager();
						ctm.updateTaskInstanceNum(collectionTaskInstance
								.getTaskDefineId());
						return "";
					} else {
						return "生成报送任务失败！";
					}
				} else {
					return "保存任务实例失败！";
				}
			}
		}
	
		
		return bsResponse;
	}


}
